﻿using Furion.DatabaseAccessor;
using System.Data;

namespace Admin.NET.WorkerService
{
    public class WorkerLog : BackgroundService
    {
        private readonly ILogger<WorkerLog> _logger;
        // 服务工厂
        private readonly IServiceScopeFactory _scopeFactory;

        public WorkerLog(ILogger<WorkerLog> logger,
                      IServiceScopeFactory scopeFactory)
        {
            _logger = logger;
            _scopeFactory = scopeFactory;
        }

        // 执行逻辑
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            using var scope = _scopeFactory.CreateScope();
            var services = scope.ServiceProvider;
            #region 清除日志
            while (!stoppingToken.IsCancellationRequested)
            {
                await DeleteLog(services);
                _logger.LogInformation("WorkerLog running at: {time}", DateTimeOffset.Now);
                //执行的方法
                await Task.Delay(24*60*60*1000, stoppingToken);
            }
            #endregion
        }

        /// <summary>
        /// 定时清除log日志
        /// </summary>
        /// <returns></returns>
        public async Task DeleteLog(IServiceProvider services)
        {
            var respository = Db.GetSqlRepository(services);
            //删除log日志
            await respository.SqlNonQueryAsync(@"TRUNCATE TABLE sys_log_ex ");
            await respository.SqlNonQueryAsync(@"TRUNCATE TABLE sys_log_op ");
            await respository.SqlNonQueryAsync(@"TRUNCATE TABLE sys_log_vis ");
        }
    }
}
